package fire.and.near.challenger.database.limit;

import java.util.Calendar;

import android.content.Context;
import android.content.SharedPreferences;

public class ChallengeConstraint {

	private static final int LIMIT = 3;

	private Context context = null;
	public static final String FILENAME = "ChallengeConstraints";
	private static final String AVAILABLE_TODAY = "available";
	private static final String DATE = "date";
	private int today = 0;
	private SharedPreferences sharedPrefs = null;

	public ChallengeConstraint(Context context) {
		this.context = context;

		sharedPrefs = context.getSharedPreferences(FILENAME,
				Context.MODE_PRIVATE);

		today = Calendar.getInstance().get(Calendar.DAY_OF_YEAR);

		if (!sharedPrefs.contains(AVAILABLE_TODAY)) {
			init();
		}
	}

	public boolean isAvailable() {
		if (today != sharedPrefs.getInt(DATE, -1)) {
			init();
			return true;
		} else if (sharedPrefs.getInt(AVAILABLE_TODAY, 0) < LIMIT) {
			return true;
		} else {
			return false;
		}
	}

	public void incAvailable() {
		SharedPreferences sharedPrefs = context.getSharedPreferences(FILENAME,
				Context.MODE_PRIVATE);

		int availableToday = sharedPrefs.getInt(AVAILABLE_TODAY, 0);
		availableToday += 1;

		SharedPreferences.Editor editor = sharedPrefs.edit();
		editor.putInt(AVAILABLE_TODAY, availableToday);
		editor.commit();
	}

	private void init() {
		SharedPreferences.Editor editor = sharedPrefs.edit();
		editor.putInt(AVAILABLE_TODAY, 0);
		editor.putInt(DATE, today);
		editor.commit();
	}
}
